# coding:utf-8
# 中兴
import paramiko
import re
from os import devnull
from network.base_connection import BaseConnection
from network.CustomizedException import *
paramiko.util.log_to_file(devnull, level=paramiko.common.WARNING)


class ZTE(BaseConnection):

    """创建和销毁ssh会话"""

    def _set_pagination_param(self):
        """
        设置设备分页相关的默认参数，若用户指定了相关参数，则优先使用用户设置的参数
        分页标识符仅在每次从缓冲区读取的命令回显的最后一行中查找
        """
        if not self.no_pagination_cmd:
            self.no_pagination_cmd = "terminal length 0"
        if self.logger:
            self.logger.debug(f"no_pagination_cmd:`{self.no_pagination_cmd}`")
        if not self.pagination_pattern:
            self.pagination_pattern = re.compile(r"--More--")
        if self.logger:
            self.logger.debug(f"pagination_pattern:`{self.pagination_pattern}`")
        if not self.next_page_cmd:
            self.next_page_cmd = " "
        if self.logger:
            self.logger.debug(f"next_page_cmd:`{self.next_page_cmd}`")

    def _set_prompt_patterns(self):
        """
        设置已知的命令提示符正则模式元组
        命令提示符仅在每次从缓冲区读取的命令回显的最后一行中查找
        """
        patterns = {
            re.compile(r"^\S+#\s*$"),
            re.compile(r"^Password:\s*$", flags=re.I),
        }
        if self.pagination_pattern:
            patterns.add(self.pagination_pattern)
        if self.prompt_patterns:
            patterns.update(self.prompt_patterns)
        self.prompt_patterns = patterns
        if self.logger:
            self.logger.debug(f"prompt_patterns:{self.prompt_patterns}")

    def _set_error_patterns(self):
        """
        设置已知的命令错误提示正则模式元组
        错误提示符会在命令回显的每行中查找，所以需要修饰符re.M
        """
        patterns = {
            re.compile(r"^%Error", flags=re.M),
            re.compile(r"^% Bad password", flags=re.M)
        }
        if self.error_patterns:
            patterns.update(self.error_patterns)
        self.error_patterns = patterns
        if self.logger:
            self.logger.debug(f"error_patterns:{self.error_patterns}")

    def _handle_passwd_update(self, res):
        """
        处理密码更改问询
        统一拒绝修改，若遇到强制修改，则抛PasswordSetException异常
        """
        # 根据res判断是否强制更改密码，强制更改则发起异常
        if re.findall(r"password:\s*$", res, re.I):
            msg = "force password update"
            if self.logger:
                self.logger.error(msg)
            raise PasswordSetException(msg)
        else:
            return ""

    """视图切换"""

    def change_mode(self, mode):
        """
        更改命令模式
        :param str mode:命令模式，可选参数：user|enable|config
        user    用户视图
        enable  特权视图
        config  全局配置视图
        """
        if mode == "user":
            self.shell("\x03")
            self.shell("disable")
            if self.logger:
                self.logger.info(f"change mode to {mode}")
        elif mode == "enable":
            res = self.shell("")
            if re.findall(r"^\S+>\s*$", res, re.M):
                res = self.shell("enable")
                if "password required" in res.lower():
                    raise PreconditionException("password required, but not set on this host")
                try:
                    self.shell(self.enable)
                except CommandExecuteException:
                    raise AuthenticationException("bad enable password")
            else:
                self.shell("\x03")
            if self.logger:
                self.logger.info(f"change mode to {mode}")
        elif mode == "config":
            res = self.shell("")
            if re.findall(r"^\S+>\s*$", res, re.M):
                res = self.shell("enable")
                if "password required" in res.lower():
                    raise PreconditionException("password required, but not set on this host")
                try:
                    self.shell(self.enable)
                except CommandExecuteException:
                    raise AuthenticationException("bad enable password")
            self.shell("\x03")
            self.shell("config terminal")
            if self.logger:
                self.logger.info(f"change mode to {mode}")
        else:
            msg = "unknown mode `{}`, the valid mode is `user`, `enable` or `config`".format(mode)
            if self.logger:
                self.logger.warning(msg)
            raise UnSupportedException(msg)

    """读写channel"""

    def shell_search_set(self, cmds, ignore=False, loop_delay=0.5, strict=False, cmd_error=True):
        """
        执行一组查询命令并进行结果检查，若任一命令错误则抛出异常，否则返回一组结果命令回显
        :param [str] cmds:要执行的命令集合
        :param bool ignore: 是否忽略错误
            True    当前命令出错不会影响下一条命令的执行
            False   当前命令出错，终止剩余命令的执行
        :param float loop_delay: 延迟时间
        :param bool strict: 是否严格执行命令提示符匹配
            True    无法匹配命令提示符时引发超时异常
            False   无法匹配命令提示符时仍会返回结果
        :param bool cmd_error: 是否对命令结果进行异常检查
        """
        if self.logger:
            self.logger.info(
            f"try to execute a set of search commands with param:ignore={ignore}, loop_delay={loop_delay}, strict={strict}, cmd_error={cmd_error}.\ncommands:{cmds}")
        self.change_mode("enable")
        while cmds:
            cmd = cmds.pop(0)
            try:
                res = self.shell(cmd=cmd, loop_delay=loop_delay, strict=strict, cmd_error=cmd_error)
                yield {"state": True, "res": res, "message": ""}
            except Exception as e:
                yield {"state": False, "res": "", "message": repr(e)}
                if not ignore:
                    if self.logger:
                        self.logger.error(
                        f"error occur while execute command `{cmd}`, terminates execution of the command set")
                    break
        if self.logger:
            self.logger.info("search command set execute finish")

    def shell_config_set(self, cmds, loop_delay=0.5, strict=False, cmd_error=True):
        """
        执行一组查询命令并进行结果检查，若任一命令错误则抛出异常
        :param [str] cmds:要执行的命令集合
        :param float loop_delay: 延迟时间
        :param bool strict: 是否严格执行命令提示符匹配
            True    无法匹配命令提示符时引发超时异常
            False   无法匹配命令提示符时仍会返回结果
        :param bool cmd_error: 是否对命令结果进行异常检查
        """
        if self.logger:
            self.logger.info(
            f"try to execute a set of config commands with param:loop_delay={loop_delay}, strict={strict}, cmd_error={cmd_error}.\ncommands:{cmds}")
        self.change_mode("config")
        while cmds:
            cmd = cmds.pop(0)
            try:
                res = self.shell(cmd=cmd, loop_delay=loop_delay, strict=strict, cmd_error=cmd_error)
                yield {"state": True, "res": res, "message": ""}
            except Exception as e:
                yield {"state": False, "res": "", "message": repr(e)}
                if self.logger:
                    self.logger.error(f"error occur while execute command `{cmd}`, terminates execution of the command set")
                break
        if self.logger:
            self.logger.info("config command set execute finish")

    """配置保存"""

    def save(self):
        """保存配置"""
        try:
            self.change_mode("enable")
            self.shell("write")
            if self.logger:
                self.logger.info("save configuration success")
        except Exception as e:
            if self.logger:
                self.logger.error(f"save configuration failure:{str(e)}")
            raise ConfigSaveException(str(e))

    """扩展功能"""

    # TODO
    # @property
    # def platform(self):
    #     """
    #     获取设备平台(操作系统)类型, 获取不到则返回None
    #     目前已支持类型：NX-OS、IOS
    #     """
    #     # 获取平台类型（操作系统类型）
    #     if not hasattr(self, "__platform"):
    #         self.__platform = None
    #         self.change_mode("enable")
    #         res = self.shell("show version brief")
    #         patterns = [
    #             re.compile(r"^Cisco Nexus Operating System \((NX-OS)\) Software", re.M),
    #             re.compile(r"Cisco (IOS) \S+ Software,", re.M)
    #         ]
    #         for pattern in patterns:
    #             platform = pattern.findall(res)
    #             if platform:
    #                 self.__platform = platform[0]
    #                 break
    # if self.logger:
#       self.logger.debug(f"return __platform: {self.__platform}")
    #     return self.__platform


